package com.shiguiwu.springmybatis.algorithm.linkedlist;


/**
 * @description: 环形单链表
 * @author: stone
 * @date: Created by 2021/3/3 23:10
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis
 */
public class RingSingleLinkedList {


    private int nums;

    private Boy first;


    public RingSingleLinkedList(int nums) {
        if (nums < 1) {
            throw new RuntimeException("初始化环形链表的大小不能小于1");
        }
        this.nums = nums;
        //创建的小孩
        Boy boy;
        //辅助变量，用于指向当前节点
        Boy curBoy = null;
        for (int i = 1; i <= nums; i++) {
            boy = new Boy(i);
            if (first == null) {
                first = boy;
                first.next = first;
                curBoy = first;
            }
            else {
                curBoy.next = boy;
                boy.next = first;
                curBoy = boy;
            }
        }
    }

    /**
     *
     *  约瑟夫问题
     * @param start 从start数，也就是初始位置
     * @param count 数count位
     */
    public void countBoy(int start, int count) {
        if (start < 1 || count < 1 || count > nums) {
            throw new RuntimeException("数据错误~~");
        }
        //定义一个下一个节点指向第一个的变量
        Boy helper = first.next;
        while (helper.next != first) {
            helper = helper.next;
        }
        for (int i = 0; i < start - 1; i++) {
            first = first.next;
            helper = helper.next;
        }

        //开始数数
        while (true) {
            if (first == helper) {
                System.out.println("出队的小孩编号：" + first.no);
                break;
            }
            for (int i = 0; i < count - 1; i++) {
                first = first.next;
                helper = helper.next;
            }

            System.out.println("出队的小孩编号：" + first.no);
            helper.next = first.next;
            first = first.next;

        }


    }








    /**
     * 打印链表
     */
    public void print() {
        this.checkNode();
        Boy temp = first;
        while (true) {
            System.out.println(temp);
            if (temp.next == first) {
                break;
            }
            temp = temp.next;
        }
    }



    public void checkNode() {
        if (first == null) {
            System.out.println("链表为空，不支持操作~~");
            throw new UnsupportedOperationException("链表为空，不支持操作~~");
        }
    }



    //小孩
//    @Data
    public static class Boy {
        //链表的顺序
        private int no;

        //下一个节点
        private Boy next;

        public Boy(int no) {
            this.no = no;
        }

        @Override
        public String toString() {
            return "Boy{" +
                    "no=" + no +
                    '}';
        }
    }
}
